package org.wmq.organizationmanagement.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.wmq.organizationmanagement.common.Result;
import org.wmq.organizationmanagement.model.dto.LoginDTO;
import org.wmq.organizationmanagement.model.dto.RegisterDTO;
import org.wmq.organizationmanagement.model.po.Admin;
import org.wmq.organizationmanagement.service.AdminService;
import org.wmq.organizationmanagement.service.LoginService;

import java.util.UUID;

@Service
@RequiredArgsConstructor
@Slf4j
public class LoginServiceImpl implements LoginService {
    private final AdminService adminService;
    private final StringRedisTemplate redisTemplate;

    @Override
    public Result<String> login(LoginDTO loginDTO) {
        Admin admin = this.adminService.getByName(loginDTO.getName());
        if (admin == null){
            log.error("登录失败，用户名不存在");
            return Result.error("登录失败，用户名不存在");
        }
        if (!admin.getPassword().equals(loginDTO.getPassword())){
            log.error("登录失败，密码错误");
            return Result.error("登录失败，密码错误");
        }
        String uuid = UUID.randomUUID().toString();
        this.redisTemplate.opsForValue().set("token:" + uuid, JSON.toJSONString(admin));
        log.info("登录成功，token为：{}", uuid);
        return Result.ok(uuid);
    }

    @Override
    public Result<Void> register(RegisterDTO registerDTO) {
        boolean nameIsExist = this.adminService.nameIsExist(registerDTO.getName());
        if (!nameIsExist){
            log.error("注册失败，用户名已存在");
            return Result.error("注册失败，用户名已存在");
        }
        Admin admin = new Admin();
        BeanUtils.copyProperties(registerDTO,admin);
        this.adminService.save(admin);
        log.info("注册成功");
        return Result.ok();
    }
}
